#!/bin/bash

set -e

BUILD_ROOT=$PWD

echo -e "\e[0;46m \e[1;32m Current Build Root: $BUILD_ROOT \e[0;0m"

BIN_PATH=$BUILD_ROOT/bin

if [ -d "$BIN_PATH" ];then
    cd "$BIN_PATH"
    rm -rf ./*
    cd ..
else
    mkdir -p "$BIN_PATH"
fi

INC_PATH=$BUILD_ROOT/include

if [ -d "$INC_PATH" ];then
    cd "$INC_PATH"
    rm -rf ./*
    cd ..
else
    mkdir -p "$INC_PATH"
fi

#cp without path

headers=$(find ./src -name '*.h')

for file in $headers
do
    temp=${file#*/}
    temp=${temp#*/}
    destFile=$INC_PATH/$temp
    destPath=${destFile%/*}
    [ -d "$destPath" ] || mkdir -p  "$destPath"
    cp -R "$file" "$destFile"
done

LIB_PATH=$BUILD_ROOT/lib

if [ -d "$LIB_PATH" ];then
    cd "$LIB_PATH"
    rm -rf ./*
    cd ..
else
    mkdir -p "$LIB_PATH"
fi

DEP_PATH=$BUILD_ROOT/dependence

if [ -d "$DEP_PATH" ];then
  echo 'exist dependence'
else
    mkdir -p "$DEP_PATH"
fi

BUILD_PATH=$BUILD_ROOT/out

if [ -d "$BUILD_PATH" ];then
    cd "$BUILD_PATH"
    rm -rf ./*
else
    mkdir -p "$BUILD_PATH"
    cd "$BUILD_PATH"
fi

cmake  "$BUILD_ROOT"
make -j4